package com.zjpavt.client.page;

import com.zjpavt.client.enums.ExtendDeviceEnum;
import com.zjpavt.client.extenddevice.GpsLigthSensationSensor;
import com.zjpavt.client.extenddevice.gps.IGpsLigthSensationDevcie;
import com.zjpavt.client.hal.*;
import com.zjpavt.client.page.abstractpage.AbstractEditablePage;
import com.zjpavt.client.page.editableunit.EditUnitNum;
import com.zjpavt.client.page.pageunit.ScreenLine;
import com.zjpavt.client.util.LoggerUtil;
import com.zjpavt.client.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * 第四页 经纬度，光照强度页面
 * @author zyc
 */
public class LocationLuxPage extends AbstractEditablePage {
    private GpsLigthSensationSensor gpsLigthSensationSensor;
    private static Logger log = LoggerFactory.getLogger(LocationLuxPage.class);
    private static final String SENSOR_INVALID = "*****";
    private static String COMMAND_INVALID = "***";
    private static final int LUX_MAX = 99999;
    private static final int LAST_TIME_MAX = 3600;

    public LocationLuxPage(int pageNum, long mRefreshPeriod) {
        super(pageNum, mRefreshPeriod);
    }

    @Override
    public void initEditUnits() {
        addEditUnit(new EditUnitNum(4, 5, 9, 0, LUX_MAX, 1));
        addEditUnit(new EditUnitNum(4, 11, 15, 0, LAST_TIME_MAX, 30));
    }

    @Override
    public void setDefaultVal() {
        LightIntensityController.LightIntensityBean lightIntensityBean = LightIntensityController.getInstance().getLightIntensityBean();
        getEditUnit(0).setCurrentVal(lightIntensityBean.getLightThreshold());
        getEditUnit(1).setCurrentVal(lightIntensityBean.getLightCommandLastTime());
    }

    @Override
    public void saveVal() {
        String lightThreshold = getEditUnit(0).getText();
        String lightCommandLastTime = getEditUnit(1).getText();
        LightIntensityController.getInstance().saveLightIntensityNotCommand(lightThreshold, lightCommandLastTime);
    }


    @Override
    public void refreshPage() {
        String location = "0.00000E,0.00000N";
        IGpsLigthSensationDevcie gpsSensor = (IGpsLigthSensationDevcie) ExtendDeviceManager.getInstance().getExtendDevice(ExtendDeviceEnum.GPS);
        IGpsLigthSensationDevcie lightSensor = (IGpsLigthSensationDevcie) ExtendDeviceManager.getInstance().getExtendDevice(ExtendDeviceEnum.LIGHT);
        int luxVal = -1;
        boolean gpsInformationUseful = false;
        String latitude = SENSOR_INVALID;
        String longitude = SENSOR_INVALID;
        if (gpsSensor!= null) {
            luxVal = (int)gpsSensor.updateLightSensationInformation().getLux();
            if (gpsSensor.isGPSUseful()) {
                location = gpsSensor.returnForFCommand();
                String[] latLng = location.split("_");
                if (latLng.length == 2) {
                    latitude = latLng[0];
                    longitude = latLng[1];
                }
            }
        }
        if(lightSensor != null) {
            luxVal = (int)lightSensor.updateLightSensationInformation().getLux();
        }
        //读取光强
        LightIntensityController.LightIntensityBean lightIntensityBean = LightIntensityController.getInstance().getLightIntensityBean();
        LedScreen.getInstance().setText(
            getPageContent(latitude, longitude, luxVal, lightIntensityBean.getLightCommand(),
                           lightIntensityBean.getLightThreshold(), lightIntensityBean.getLightCommandLastTime()));
    }

    /**
     *
     * @param latitude		经度
     * @param longitude		纬度
     * @param luxVal		光照强度
     * @param command		光照指令
     * @param luxThreshold	光照阈值
     * @param lastTime		单次持续时间
     * @return				页面显示对象
     */
    private List<ScreenLine> getPageContent(String latitude, String longitude, int luxVal, String command, int luxThreshold, int lastTime) {
        List<ScreenLine> result = new ArrayList<>();
        String luxValStr;
        if (luxVal < 0 || luxVal >= LUX_MAX) {
            luxValStr = SENSOR_INVALID;
        } else {
            luxValStr = String.format("%05d", luxVal);
        }
        if (StringUtil.isNullOrEmpty(command)) {
            command = COMMAND_INVALID;
        } else {
            try {
                command=StringUtil.formatCommand(StringUtil.bin2Hex(command,true),LoopManager.getInstance().getLoopNum()/4);
                command = command.length()>4 ? command.substring(0,4):command;
            } catch (StringIndexOutOfBoundsException e) {
                LoggerUtil.convertException2String(e);
            }
        }
//		log.debug(" command :"+StringUtil.bin2Hex(command,true).length());
        String luxThresholdStr;
        if (luxThreshold < 0 || luxThreshold >= LUX_MAX) {
            luxThreshold = 0;
        }
        luxThresholdStr = String.format("%05d", luxThreshold);
        String lastTimeStr;
        if (lastTime < 0 || lastTime >= LAST_TIME_MAX) {
            lastTime = 0;
        }
        lastTimeStr = String.format("%05d", lastTime);
        result.add(new ScreenLine.ScreenLineBuilder().text(longitude).pageNum(getPageNum()).build());
        result.add(new ScreenLine.ScreenLineBuilder().text(latitude).build());
        result.add(new ScreenLine.ScreenLineBuilder().text("LUN:" + luxValStr + " " + command).build());
        result.add(new ScreenLine.ScreenLineBuilder().text("lux:" + luxThresholdStr + "_" + lastTimeStr).build());
        return result;
    }
}
